import React, { Component } from 'react'
import {
    Navigator,
    StyleSheet,
    Platform,
    BackAndroid
} from 'react-native'

import Constants from '../../Constants'

export default class CustomNavigator extends Component {
    constructor(props) {
        super(props)
        this.firstClick = 0
        this.handleBackAndroid = this.handleBackAndroid.bind(this)
        this.handleNav = nav => {
            this.navigator = nav
        }
    }

    static propTypes = {
        configureScene: React.PropTypes.func.isRequired,
        renderScene: React.PropTypes.func.isRequired,
        routeMapper: React.PropTypes.func.isRequired,
        initRoute: React.PropTypes.object.isRequired
    }

    componentDidMount() {
        if (Platform.OS === 'android') {
            BackAndroid.addEventListener('hardwareBackPress', this.handleBackAndroid);
        }
    }

    componentWillUnmount() {
        if (Platform.OS === 'android') {
            BackAndroid.removeEventListener('hardwareBackPress', this.handleBackAndroid);
        }
    }

    handleBackAndroid() {
        const navigator = this.navigator
        if (navigator && navigator.getCurrentRoutes().length > 1) {
            navigator.pop()
            return true
        } else {
            const timestamp = (new Date()).valueOf()
            if (timestamp - this.firstClick > 500) {
                this.firstClick = timestamp
                return true
            } else {
                return false
            }
        }
    }

    render() {
        let navStyle = Platform.OS === 'android' ? style.navAndroid : style.navIOS
        return (
            <Navigator
                ref={this.handleNav}
                navigationBar={
                 <Navigator.NavigationBar
                    style = {navStyle}
                    routeMapper = {this.props.routeMapper()}
                 />
              }
                initialRoute={this.props.initRoute}
                configureScene={this.props.configureScene}
                renderScene={this.props.renderScene}
            />
        )
    }
}

const BLUE = '#2db7f5'
const FONTCOLOR = 'white'

const style = StyleSheet.create({
    navAndroid: {
        backgroundColor: BLUE,
        height: 50
    },
    navIOS: {
        backgroundColor: BLUE,
        height: 64
    },
    navBtn: {
        fontSize: 15,
        marginTop: 13,
        marginLeft: 5,
        height: 50,
        color: FONTCOLOR
    },
})
